package com.ocom.devicehttp.controller;

import com.ocom.common.constant.MachineHttpUrl;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.JsonResponse;
import com.ocom.common.utils.SignUtils;
import com.ocom.devicehttp.client.AiotClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/8/24
 **/
@Slf4j
@RestController
public class OtaController {

	@Autowired
	AiotClientService aiotClientService;

	@PostMapping(MachineHttpUrl.URL_OtaUpdate)
	public JsonResponse OtaUpdate(@RequestBody Map<String,Object> map) {

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		map.put("ts",request.getHeader("Ts"));

		SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
		for(Map.Entry<String, Object> entry : map.entrySet()){
			sortedMap.put(entry.getKey(),entry.getValue());
		}

		String sign1= SignUtils.createSign(sortedMap,"2D7E7C96-DAC5-4526-96C3-C60CDEC4B120");

		if(!request.getHeader("Sign").equals(sign1)){
			return JsonResponse.error("验签失败");
		}

		Result result = aiotClientService.getOtaUpdate((String) map.get("machNo"),(String) map.get("otaVersion"));
		log.info("ota升级结果： 【{}】",result);
		if(result.getCode()!=200){
			return JsonResponse.error("不需要更新");
		}

		return JsonResponse.success(result.getData());
	}
}
